﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
using System.Configuration;

namespace SimulatedDevice
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Simulated device\n");
            deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("myFirstDevice", deviceKey));

            SendDeviceToCloudMessagesAsync();
            Console.ReadLine();

        }

        static DeviceClient deviceClient;
        static string iotHubUri = "bkiothub.azure-devices.cn";
        static string deviceKey = "yumoNx1cD2OkrS9YoTWIPr5Ej2UKUKXF2S4rQiMeNzY=";


        private static async void SendDeviceToCloudMessagesAsync()
        {
            Random rand = new Random(1);
            int min = int.Parse(ConfigurationSettings.AppSettings["minp"].ToString());
            int max = int.Parse(ConfigurationSettings.AppSettings["maxp"].ToString());
            Random devicerand = new Random();

            while (true)
            {
                int pcount = rand.Next(min, max);
                //var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
                //string teststring = String.Format("device0;12;{0};0", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                int device = devicerand.Next(1, 4);
                string teststring = "";
                if (device == 1)
                {
                    teststring = String.Format("device0;{0};{1};0", pcount, DateTime.Now.ToString());
                }
                else if (device == 2)
                {
                    teststring = String.Format("device1;{0};{1};0", pcount, DateTime.Now.ToString());
                }
                else
                {
                    teststring = String.Format("device2;{0};{1};0", pcount, DateTime.Now.ToString());
                }
                var message = new Message(Encoding.ASCII.GetBytes(teststring));

                await deviceClient.SendEventAsync(message);
                Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, teststring);

                Task.Delay(1000).Wait();
            }
        }

    }
}
